/*
require  dataColumn.js
require  scrollpanel.js
require  dragdrop.js
require  dropdownlist.js
require qs_watchlist_en_us.js
 */
if (!Util) {
    var Util = {};
}
//Plugin: custom view
Util.CustomView = function(continer,config,callbacks){
    this.callback = {
        onValidation:function(){
            return true;
        }
    };
    $.extend(true,this.callback,callbacks);
    var qslan=QS_Lang.watchlist;
    this.config = {
        maxCount:15,
        autoClose:true,
        maxValid:true,
        showClose:false,
        setData:{},
        colData:{},
        dataSource:{}
    };
    $.extend(true,this.config,{isAPI:false},config);
    this.continer=continer||$("body");
    this.dataScrollPNleft = null;
    this.dataScrollPNright = null;
    this.cacheColumns=[];
    this.html = '<div class="bd"><div class="content">' +
    '<div class="colset"><h3>'+qslan["setlabel"]+'</h3><div class="hd clearfix"></div><div class="cols clearfix"><div class="data"></div></div><h4 class="qs-choice-prompt"></h4></div>' +
    '<div class="currcols"><h3>'+qslan["viewlabel"]+'</h3><div class="hd"></div><div class="ddwrap"><div class="cols"><div class="data"><ul></ul></div></div></div><h4>'+qslan["dragprompt"]+'</h4></div>' +
    '</div></div>' +
    '<div class="ft"><div class="action"><a class="qs-ui-btn save" href="javascript:void(0)">'+qslan["confirm"]+'</a>'+(this.config.showClose?'<a class="qs-ui-btn close" href="javascript:void(0)">'+qslan["close"]+'</a>':"")+'</div></div>';
    this.colSetData ={
        'gen':{
            txt: 'General',
            val: 'gen',
            show: true
        },
        'pri':{
            txt: 'Price and Market Data',
            val: 'pri',
            show: true
        },
        'mor':{
            txt: 'Morningstar Rating/Grades',
            val: 'mor',
            show: true
        },
        'por':{
            txt: 'Portfolio',
            val: 'por',
            show: true
        },
        'val':{
            txt: 'Valuation Measures',
            val: 'val',
            show: true
        },
        'div':{
            txt: 'Dividends',
            val: 'div',
            show: true
        },
        'tot':{
            txt: 'Total Return',
            val: 'tot',
            show: true
        }
    };
    $.extend(true,this.colSetData,this.config.setData);
    this.cols = {
        "gen": ["Alert","os378","st153","st159","Name","R/D","la03z","Symbol","Up/Down","currency","country"],
        "pri": ["LastPrice","ClosePrice","MiddlePrice","Spread","LastMarket","Chg","Chg%","os060","+/- NAV",
                "BidPrice","BidSize","AskPrice","AskSize","RVolume","Volume","VWAP","st168","st169","st109",
                "st106","HighPrice","LowPrice","Time"],
        "mor": ["st200","st202","st201","st181","st206"],
        "por":["MarketValue","P/L","P/Lpc","NumOfShares","PurchaseDate","PurchasePrice","Comm"],
        "val":["st198","st263","st408"],
        "div":["pm032","sta65"],
        'tot': ["pd003","pd005","pd007","pd009","pm493","pd00d","pd014","pd00f","pd00h","pm494","pm495","pd00b"]
    };
    $.extend(true,this.cols,this.config.colData);
    this.colsCache={};
    this._init();
};
Util.CustomView.prototype = {
    //find which set the col belong to
    _getSetbyKey: function(colKey){
        for (var set in this.cols) {
            if($.inArray(colKey,this.cols[set])>-1){
                return set;
            }
        }
        return null;
    },
    _checkIsSelectedAll: function(set){
        for (var i in this.colsCache[set]) {
            if (!this.colsCache[set][i].checked) {
                return false;
            }
        }
        this._fnCheckCol(this.colsetCol.find('li[val="0"]'), true);
        return true;
    },
    _addColToCurrentCol: function(colKey){//need update
        if (this.currentCol.find('li[val="' + colKey + '"]').length < 1) {
            var li = document.createElement('li');
            li.colKey = colKey;
            li.setAttribute('val', colKey);
            var txt = this._getTxt(colKey);
            if (colKey == 'R/D') {
                txt = 'R/D';
            }
            else 
                if (colKey == 'Alert') {
                    txt = 'Alert';
                }
                else 
                    if (colKey == 'Up/Down') {
                        txt = 'Up/Down';
                    }
            li.txt = txt;
            li.innerHTML = '<a href="javascript:void(0)"><em>' + txt + '</em><span>x</span></a>';
            var self = this;
            this.currentCol.find('div.data').children('ul').append(li);
            var drag = new Util.Dragable($(li), {
                onDragStart: function(e, proxy){
                    proxy.html(li.txt);
                    proxy.dataObj = li.colKey;
                    proxy.$obj = $(li);
                    proxy.selectObj = self;
                },
                onDrag: function(e, proxy){
                
                }
            }, {
                group: "customview"
            });
            var drop = new Util.Dropable($(li), {
                onEnter: function(e, proxy){
                    if (proxy.selectObj && proxy.selectObj == self) {
                        $(li).addClass('customview-drop');
                        //if move to a samilar obj
                    }
                },
                onDrop: function(e, proxy){
                    if (proxy.selectObj && proxy.selectObj == self) {
                        $(li).removeClass('customview-drop');
                        if (proxy.dataObj && proxy.dataObj != li.colKey) {
                            proxy.$obj.insertBefore($(e.target).closest("li"));
                        }
                    }
                },
                onOut: function(e, proxy){
                    if (proxy.selectObj && proxy.selectObj == self) {
                        $(li).removeClass('customview-drop');
                    }
                }
            }, {
                group: "customview"
            });
            if (this.dataScrollPNright) {
                this.dataScrollPNright.reSize(193, 230);
            }
        }
    },
    _fnColsetSelect: function(set){//t:columnsetname v:columnsetnamevalue
        var html = '<ul><li class="rtq-chkbox rtq-chkbox_off" val="0">Select All</li>';
        var chkstr = '';
        for (var i in this.colsCache[set]) {
            if (this.colsCache[set][i].checked == true) {
                this._addColToCurrentCol(i);
                chkstr = '';
            }
            else {
                chkstr = ' rtq-chkbox_off';
            }
            html += '<li class="rtq-chkbox' + chkstr + '" val="' + i + '">' + this._getTxt(i) + '</li>';
        }
        this.pn.find('.colset .cols .data').html(html + '</ul>');
        this._checkIsSelectedAll(set);
        if (this.dataScrollPNleft) {
            this.dataScrollPNleft.reSize(193, 205);
        }
    },
    _fnCheckCol: function(el, Checked){
        var checked = typeof Checked != 'undefined' ? Checked : el.hasClass('rtq-chkbox_off');
        var colKey = el.attr('val');
        el.toggleClass('rtq-chkbox_off', !checked);
        if (colKey == 0) {
            return;
        }
        if (checked) {
            this._addColToCurrentCol(colKey);
        }
        else {
            this._fnCheckCol(this.colsetCol.find('li[val="0"]'), false);
            this.currentCol.find('li[val="' + colKey + '"]').remove();
            if (!this.dataScrollPNright) {
                this.dataScrollPNright = new Util.ScrollPanel(this.pn.find('.currcols .cols .data'), {
                    showX: false
                });
                this.dataScrollPNright.reSize();
            }
            else {
                this.dataScrollPNright.reSize();
            }
        }
        var set = this._getSetbyKey(colKey);
        this.colsCache[set][colKey].checked = checked;
        this._checkIsSelectedAll(set);
        this._leaveItemPrompt();
    },
    _getDDLData:function(){
        var list=[],temp={};
        for(var type in this.colSetData){
            temp = this.colSetData[type];
            if(temp.show){
                list.push({txt:temp.txt,val:temp.val});
                this._genColsCache(type);
            }
        }
        return list;
    },
    _genColsCache:function(set){
        var cols = this.cols[set];
        this.colsCache[set]={};
        for(var i =0,l=cols.length;i<l;i++){
            this.colsCache[set][cols[i]]={checked:false};
        }
    },
    _createDom: function(){
        this.pn = $('<div class="rtq-wl-ctview">').html(this.html);
        this.colsetCol = this.pn.find('.colset .cols');
        this.currentCol = this.pn.find('.currcols .cols');
        this.leftpropmt = this.pn.find('.colset .qs-choice-prompt');
        var self = this;
        this.ddlColSet = new Util.DropDownList(this.pn.find('.colset .hd')[0], function(t, v){
            self._fnColsetSelect(v);
        }, this._getDDLData(), {
            width: 193
        });
        this.continer.append(this.pn);
    },
    _bindEvent: function(){
        var self = this;
        self.colsetCol.click(function(e){
            if (e.target.tagName.toLowerCase() == 'li') {
                var el = $(e.target);
                var val = el.attr('val');
                if (val == 0) {
                    var checked = el.hasClass('rtq-chkbox_off');
                    self.colsetCol.find('li').each(function(i){
                        self._fnCheckCol($(this), checked);
                    });
                }
                else {
                    self._fnCheckCol(el);
                }
            }
        });
        this.currentCol.click(function(e){
            var tag = e.target.tagName.toLowerCase();
            e.preventDefault();
            //del col
            if (tag == 'span') {
                var el = $(e.target).parent().parent();
                var colKey = el.attr('val');
                var set = self._getSetbyKey(colKey);
                el.remove();
                self._leaveItemPrompt();
                if (!self.dataScrollPNright) {
                    self.dataScrollPNright = new Util.ScrollPanel(self.pn.find('.currcols .cols .data'), {
                        showX: false
                    });
                    self.dataScrollPNright.reSize();
                }
                else {
                    self.dataScrollPNright.reSize();
                }
                if (self.colsetCol.find('li[val="' + colKey + '"]').length > 0) {
                    self._fnCheckCol(self.colsetCol.find('li[val="' + colKey + '"]'), false);
                }
                self.colsCache[set][colKey].checked = false;
            }
        });
        this.pn.find('.action .close').bind('click', function(e){
            self.hide();
        });
        this.pn.find('.action .save').click(function(e){
            var sltCols = self.currentCol.find('li');
            if (sltCols.length < 1) {
                Util.message("You must choose at least one item, Please.");
            }else  if(sltCols.length>self.config.maxCount){
                Util.message(String.format("Only {0} maximum items are allowed.",self.config.maxCount));
            }else{
                var colCfg = [];
                sltCols.each(function(i){
                    //only save dataindex and width
                    colCfg.push({
                        dataIndex: this.colKey,
                        width: self._getWidth(this.colKey)
                    });
                });
                self.cacheColumns=[];

                if(self.callback.onValidation(colCfg)){
                    if(typeof self.callback.onConfirm=="function"){
                        self.callback.onConfirm(colCfg);
                    }
                }
                if(self.config.autoClose){
                    self.hide();
                };
            }
        });
    },
    _leaveItemPrompt:function(){
        if(this.config.maxValid){
            var total=this.currentCol.find('li').length;
            //this.maxCount
            if (total <=this.config.maxCount) {
                this.leftpropmt.text(String.format("The rest of selectable criterion: {0}", this.config.maxCount - total));
            }else{
                this.leftpropmt.text(String.format("{0} selected criterions are more than the maximum of {1}", total,this.config.maxCount));
            }
        }
    },
    _init: function(){
        if(Util.isValid(QSAPI.Widget.Columns,true,true)){
            this.config.dataSource = $.extend(true,QSAPI.Widget.Columns,this.config.dataSource);
        }
        this._createDom();
        this._bindEvent();
        this.hide();
    },
    _show:function(){
        this.continer.show();
    },
    hide:function(){
        this.continer.hide();
    },
    _getWidth:function(key){
        for(var i=0,l=this.cacheColumns.length;i<l;i++){
            if(this.cacheColumns[i]["dataIndex"]==key){
                if(this.cacheColumns[i]["width"]){
                    return this.cacheColumns[i]["width"];
                }
            }
        }
        return this.config.dataSource[key]["width"]||80; //width should be get from cache
    },
    _getTxt:function(key){
        return this.config.dataSource[key]["txt"]||key;
    },

    _buildData: function(data){
        this.currentCol.find('div.data').children('ul').empty();
        //reset all cols to unchecked
        for (var set in this.colsCache) {
            for (var i in this.colsCache[set]) {
                this.colsCache[set][i].checked = false;
            }
        }
        //add checked cols to currentCol div
        var dataMap, set, colKey;
        for (var j = 0; j < data.length; j++) {
            colKey = data[j].dataIndex;
            set = this._getSetbyKey(colKey);
            if (set) {
                this.colsCache[set][colKey].checked = true;
                this._addColToCurrentCol(colKey);
            }
        }
    },
    _extendDataIndex:function(views){
        var viewKey = [];
        for ( var k = 0, j = views.length; k < j; k++) {
            if(typeof views[k]!='object'){
                viewKey.push({
                    "dataIndex" : $.trim(views[k])
                });
            }else{
                viewKey.push(views[k]);
            }
        }
        return viewKey;
    },
    open: function(defaultColumns){ //ViewObj [{dataIndex: 'Name', width: '123'},{}]
        if(Util.isValid(defaultColumns,true,true)&&defaultColumns.length>0){
            this.cacheColumns=this._extendDataIndex(defaultColumns);
            this._buildData(this.cacheColumns);
        }
        this.ddlColSet.selectItemByIndex(0);
        this._show();
        this._leaveItemPrompt();
        if (!this.dataScrollPNleft) {
            this.dataScrollPNleft = new Util.ScrollPanel(this.pn.find('.colset .cols .data'), {
                showX: false
            });
            this.dataScrollPNleft.reSize(193, 205);
        }
        else {
            this.dataScrollPNleft.reSize(193, 205);
        }
        if (!this.dataScrollPNright) {
            this.dataScrollPNright = new Util.ScrollPanel(this.pn.find('.currcols .cols .data'), {
                showX: false
            });
            this.dataScrollPNright.reSize(193, 230);
        }
        else {
            this.dataScrollPNright.reSize(193, 230);
        }
    }
};